<template>
  <FullPageModal
    v-model:visible="innerVisible"
    custom-footer
    :title="t('aiot.serviceApply.addWorkOrder')"
    :get-container="getContainer"
    :inset-cls="insetCls ? insetCls : undefined"
    @open="open"
  >
    <div class="w-px-1 mx-auto">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane v-for="item of createWorkOrderArr" :key="item.key" :style="item.style">
          <template #tab>
            <Icon :type="item.key === activeKey ? item.icon : item.unicon" class="text-xl text-color-main" />
            <span> {{ item.tabName }} </span>
          </template>
        </a-tab-pane>
      </a-tabs>
      <DynamicForm ref="workOrderIns" :model="model" :model-form-setting="modelFormSetting" :force-flex-row="true" />
    </div>
    <template #footer>
      <a-button @click="handleCancelFn">{{ t("common.cancel") }}</a-button>
      <a-button type="primary" @click="ok">{{ t("common.ok") }}</a-button>
      <!-- <a-button type="primary" @click="dispatchWorkOrderFn">{{ t("aiot.serviceApply.dispatchWorkOrder") }}</a-button> -->
    </template>
    <ChooseCustomerModal v-model:show="chooseCustomerVisible" @ok="handleChooseCustomer" />
    <ChooseProjectModal v-model:show="chooseProjectVisible" @ok="handleChooseProject" />
    <ChooseEquipmentModal
      v-model:show="chooseEquipmentVisible"
      :project-id="model.projectId"
      @ok="handleChooseEquipement"
    />
    <LocationDialog v-model:visible="locDgVisible" @ok="chooseLoc" />
    <DispatchModal :options="dispatchOptions" @ok="successFn" />
  </FullPageModal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import { nextTick, ref, watch } from "vue";
import FullPageModal from "/@/components/FullPageModal.vue";
import LocationDialog from "/@/components/LocationDialog.vue";
import Icon from "/@/components/Icon.vue";
import { useWorkOrderModal } from "./useWorkOrderModal";
import ChooseCustomerModal from "/@/components/ChooseCustomerModal.vue";
import ChooseProjectModal from "/@/components/ChooseProjectModal.vue";
import ChooseEquipmentModal from "/@/components/ChooseEquipmentModal.vue";
import { createWorkOrders } from "/@/api/aiot/serviceWorkOrder";
import { WorkOrderItem } from "/@/api/aiot/serviceWorkOrder/models";
import { DispatchOptions } from "/@/api/aiot/serviceApply/models";
import { PartialAlarmItem, TransWorkOrderReq } from "/@/api/aiot/alarm/models";
import dayjs from "dayjs";
import { transferToWorkOrder } from "/@/api/aiot/alarm";
import { getProjectVoByProjectId } from "/@/api/aiot/projectManage";

const { t } = useI18n();
const props = withDefaults(
  defineProps<{
    visible: boolean;
    insetCls?: string;
    equipment?: PartialAlarmItem;
    getContainer?: () => HTMLElement;
  }>(),
  {}
);
const activeKey = ref<string>("REPAIR");
const {
  workOrderIns,
  model,
  modelFormSetting,
  createWorkOrderArr,
  handleChooseCustomer,
  handleChooseProject,
  chooseCustomerVisible,
  chooseProjectVisible,
  chooseEquipmentVisible,
  handleChooseEquipement,
  locDgVisible,
  chooseLoc,
} = useWorkOrderModal(props.equipment ? true : false);
const dispatchOptions = ref<DispatchOptions>({ workOrderId: "", projectId: "" });

const emits = defineEmits(["create", "update:visible", "ok", "update:equipment"]);
const innerVisible = ref(false);
const workOrderId = ref("");
watch(
  () => props.visible,
  (v) => {
    innerVisible.value = v;
    if (!v) {
      emits("update:equipment", {});
    }
  }
);
watch(activeKey, (v) => {
  model.value.workOrderType = v;
});
watch(
  () => props.equipment,
  async (v) => {
    console.info("v--->", v);
    console.info("model.value==>", model.value);
    model.value.equipmentId = v?.equipmentId;
    model.value.projectId = v?.projectId;
    model.value.projectName = v?.projectName;
    model.value.equipmentName = v?.equipmentName;
    model.value.happenTime = v?.createdOn ? dayjs(v.createdOn).format(t("common.dateTimeFormatStr1")) : "";
    let projectInfo = await getProjectVoByProjectId({ projectId: v?.projectId || "" });
    model.value.customerId = projectInfo?.customerId;
    model.value.customerName = projectInfo?.customerName;
    model.value.address = projectInfo?.address;
    model.value.contactsPerson = projectInfo?.contactPerson;
    model.value.contactsPhone = projectInfo?.contactPhone;
  }
);
function successFn() {
  emits("ok");
}
function dispatchWorkOrderFn() {
  workOrderIns.value?.validate().then(async () => {
    let data: WorkOrderItem = { ...model.value };
    let req;
    if (props.equipment?.alarmEventId) {
      let obj: TransWorkOrderReq = { workOrdersSaveRequest: data, alarmEventId: props.equipment.alarmEventId };
      req = await transferToWorkOrder(obj);
    } else {
      req = await createWorkOrders(data);
    }
    if (req?.workOrderId) {
      workOrderId.value = req?.workOrderId || "";
      dispatchOptions.value = {
        workOrderId: req?.workOrderId || "",
        projectId: model.value.projectId || "",
      };
    }
    // req && emits("ok");
  });
}
function open() {
  nextTick(() => {
    workOrderIns.value?.initFormItemComponentData();
  });
}
function handleCancelFn() {
  emits("update:visible", false);
}
//第一次打开
let firstShow = true;
watch(innerVisible, (v) => {
  emits("update:visible", v);
  if (!v) {
    workOrderIns.value?.resetFields();
  }
  if (firstShow) {
    firstShow = false;
  }
});
//窗口关闭
function cancel() {
  emits("update:visible", false);
}

const content = ref<HTMLDivElement>();
async function ok(isContinue) {
  workOrderIns.value?.validate().then(async () => {
    let data: WorkOrderItem = { ...model.value };
    let req;
    if (props.equipment?.alarmEventId) {
      let obj: TransWorkOrderReq = { workOrdersSaveRequest: data, alarmEventId: props.equipment.alarmEventId };
      req = await transferToWorkOrder(obj);
    } else {
      req = await createWorkOrders(data);
    }
    console.info("req===>", req);
    // model.value.faultImagesUrl = [];
    if (req?.workOrderId || (props.equipment?.alarmEventId && req)) {
      emits("create");
    }
  });
}
</script>
